<?php
namespace App\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class Base extends \Eloquent
{

    public $page = 1;
    public $sum = 10;
    public $start = 0;
    public $user_info = null;
    public $fields = [];

    public function initPage(){
        $this->page = request()->input('page',1);
        $this->sum = request()->input('sum',10);

        $this->start = ($this->page-1)*$this->sum;
    }

    public function getColumns($table){
        return Schema::getColumnListing($table);
    }

    public function formatRequest(){
        $data = array();
        $params = request()->all();

        foreach ($params as $key=>$param){
            if(in_array($key,$this->fields)){
                $data[$key]=$param;
            }
        }
        return $data;
    }

    public function toArray()
    {
        try{
            return parent::toArray(); // TODO: Change the autogenerated stub
        }catch (\Exception $e){
            return [];
        }
    }

    public function added($data = null){
        if(!$data) $data = $this->formatRequest();

        return  self::insertGetId($data);
    }

    public function updateByCondition($condition,$data){
        if(self::findMany($condition)) {
            unset($data['id']);
            self::where($condition)->update($data);
            return true;
        }else{
            return false;
        }
    }

    public function updateById($id,$data){
        if(self::find($id)) {
            unset($data['id']);
            self::where('id',$id)->update($data);
            return true;
        }else{
            return false;
        }

    }

    public function getOne($id,$condition="*"){
        return self::select(DB::raw($condition))->where('id',$id)->first();
    }

    public function del($id,$real=false){
        if(self::find($id)){
            if($real){
                self::where('id',$id)->delete();
            }else{
                $this->updateByCondition(['id'=>$id],['is_del'=>1]);
            }
            return true;
        }else{
            return false;
        }

    }
    public function isExits($where){
        return self::where($where)->exists();
    }

}